package com.lsl.gulimall.product.service.impl;

import com.lsl.common.constant.ProductConstant;
import com.lsl.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.lsl.gulimall.product.entity.AttrGroupEntity;
import com.lsl.gulimall.product.entity.CategoryEntity;
import com.lsl.gulimall.product.service.AttrAttrgroupRelationService;
import com.lsl.gulimall.product.service.AttrGroupService;
import com.lsl.gulimall.product.service.CategoryService;
import com.lsl.gulimall.product.vo.request.AttrInVo;
import com.lsl.gulimall.product.vo.response.AttrGroupWithAttrsOutVo;
import com.lsl.gulimall.product.vo.response.AttrOutVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsl.common.utils.PageUtils;
import com.lsl.common.utils.Query;

import com.lsl.gulimall.product.dao.AttrDao;
import com.lsl.gulimall.product.entity.AttrEntity;
import com.lsl.gulimall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    AttrService attrService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getBaseAttrList(Map<String, Object> params, String attrType, Long catelogId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.eq("attr_id", key).or().like("attr_name", key);
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper);
        List<AttrEntity> attrEntityList = page.getRecords();
        ArrayList<AttrOutVo> attrOutVoArrayList = new ArrayList<>();
        if (attrEntityList != null && attrEntityList.size() > 0) {
            for (AttrEntity attrEntity : attrEntityList) {
                Long entityCatelogId = attrEntity.getCatelogId();
                //通过catelog_id查询CategoryEntity
                Long[] catelogPath = categoryService.findCatelogPath(entityCatelogId);
                CategoryEntity categoryEntity = categoryService.getById(entityCatelogId);

                //通过attr_id查询AttrAttrgroupRelationEntity
                QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
                attrAttrgroupRelationEntityQueryWrapper.eq("attr_id", attrEntity.getAttrId());
                AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationService.getOne(attrAttrgroupRelationEntityQueryWrapper);


                AttrOutVo attrOutVo = new AttrOutVo();
                BeanUtils.copyProperties(attrEntity, attrOutVo);
                attrOutVo.setCatelogPath(catelogPath);
                attrOutVo.setCatelogName(categoryEntity.getName());
                if (attrgroupRelationEntity != null) {
                    //通过group_id查询AttrGroupEntity
                    AttrGroupEntity groupEntity = attrGroupService.getById(attrgroupRelationEntity.getAttrGroupId());
                    attrOutVo.setGroupName(groupEntity.getAttrGroupName());
                }
                attrOutVoArrayList.add(attrOutVo);
            }
        }
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrOutVoArrayList);
        return pageUtils;
    }

    @Override
    public void saveAttr(AttrInVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();


        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public void deleteByIds(List<Long> attrIds) {
        this.getBaseMapper().deleteBatchIds(attrIds);
        for (Long attrId : attrIds) {
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id", attrId);
            attrAttrgroupRelationService.remove(queryWrapper);
        }
    }

    @Override
    public AttrOutVo getAttrInfoById(Long attrId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id", attrId);
        AttrEntity attrEntity = this.getOne(queryWrapper);

        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
        attrAttrgroupRelationEntityQueryWrapper.eq("attr_id", attrId);
        AttrOutVo attrOutVo = new AttrOutVo();

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationService.getOne(attrAttrgroupRelationEntityQueryWrapper);
            if (attrgroupRelationEntity != null) {
                AttrGroupEntity groupEntity = attrGroupService.getById(attrgroupRelationEntity.getAttrGroupId());
                if (groupEntity != null) {
                    attrOutVo.setGroupName(groupEntity.getAttrGroupName());
                    attrOutVo.setAttrGroupId(groupEntity.getAttrGroupId());
                }
            }
        }

        BeanUtils.copyProperties(attrEntity, attrOutVo);
        attrOutVo.setCatelogPath(catelogPath);
        return attrOutVo;
    }

    @Override
    public void updateAttr(AttrInVo attr) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        QueryWrapper<AttrAttrgroupRelationEntity> attrgroupRelationEntityQueryWrapper = new QueryWrapper<>();


        queryWrapper.eq("attr_id", attr.getAttrId());
        attrgroupRelationEntityQueryWrapper.eq("attr_id", attr.getAttrId());
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getOne(attrgroupRelationEntityQueryWrapper);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            if (attrAttrgroupRelationEntity != null) {
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationService.update(attrAttrgroupRelationEntity, attrgroupRelationEntityQueryWrapper);
            }
        }
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.update(attrEntity, queryWrapper);
    }

    @Override
    public PageUtils getNoattrRelation(Map<String, Object> params, Long groupId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        //当前分组只能关联当前分类下别的分组没有引用的属性
        AttrGroupEntity groupEntity = attrGroupService.getById(groupId);
        Long catelogId = groupEntity.getCatelogId();
        QueryWrapper<AttrGroupEntity> attrGroupEntityQueryWrapper = new QueryWrapper<>();
        attrGroupEntityQueryWrapper.eq("catelog_id", catelogId);
        queryWrapper.eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        List<AttrGroupEntity> attrGroupEntities = attrGroupService.list(attrGroupEntityQueryWrapper);
        if (attrGroupEntities != null && attrGroupEntities.size() > 0) {
            //查询该分类分组下的所有属性
            List<Long> GroupIds = attrGroupEntities.stream().map(
                    (item) -> item.getAttrGroupId()
            ).collect(Collectors.toList());

            //通过groupId获取pms_attr_attrgroup_relation
            QueryWrapper<AttrAttrgroupRelationEntity> relationEntityQueryWrapper = new QueryWrapper<>();
            relationEntityQueryWrapper.in("attr_group_id", GroupIds);
            List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationService.list(relationEntityQueryWrapper);

            //通过attrId获取该分类下分组所有属性
            if (relationEntityList != null && relationEntityList.size() > 0) {
                //查询该分类分组下的所有属性
                List<Long> AttrIds = relationEntityList.stream().map(
                        (item) -> item.getAttrId()
                ).collect(Collectors.toList());
                if (AttrIds != null && AttrIds.size() > 0) {
                    //获取不在该分类分组下的属性
                    queryWrapper.notIn("attr_id", AttrIds);
                }
            }
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public List<AttrOutVo> getattrRelation(Long groupId) {
        //通过groupId获取pms_attr_attrgroup_relation
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_group_id", groupId);
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.list(queryWrapper);

        ArrayList<AttrOutVo> attrOutVos = new ArrayList<>();
        List<Long> attrIds = attrAttrgroupRelationEntities.stream().map(
                (item) ->
                        item.getAttrId()
        ).collect(Collectors.toList());
        if (attrIds != null && attrIds.size() > 0) {
            List<AttrEntity> attrEntities = this.baseMapper.selectBatchIds(attrIds);
            if (attrEntities != null && attrEntities.size() > 0) {
                for (AttrEntity attrEntity : attrEntities) {
                    AttrOutVo outVo = new AttrOutVo();
                    BeanUtils.copyProperties(attrEntity, outVo);
                    attrOutVos.add(outVo);
                }
            }
        }
        return attrOutVos;
    }

    @Override
    public List<AttrGroupWithAttrsOutVo> getWithAttrByCateLogId(Long catelogId) {
        ArrayList<AttrGroupWithAttrsOutVo> attrGroupWithAttrsOutVos = new ArrayList<>();
        QueryWrapper<AttrGroupEntity> attrGroupEntityQueryWrapper = new QueryWrapper<>();
        attrGroupEntityQueryWrapper.eq("catelog_id", catelogId);

        //查找该分类下有多少分组
        List<AttrGroupEntity> attrGroupEntityEntities = attrGroupService.list(attrGroupEntityQueryWrapper);
        if (attrGroupEntityEntities != null && attrGroupEntityEntities.size() > 0) {
            for (AttrGroupEntity attrGroupEntity : attrGroupEntityEntities) {
                AttrGroupWithAttrsOutVo attrGroupWithAttrsOutVo = new AttrGroupWithAttrsOutVo();
                BeanUtils.copyProperties(attrGroupEntity, attrGroupWithAttrsOutVo);

                //通过attr_group_id查询pms_attr_attrgroup_relation
                Long attrGroupId = attrGroupEntity.getAttrGroupId();
                QueryWrapper<AttrAttrgroupRelationEntity> attrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
                attrgroupRelationEntityQueryWrapper.eq("attr_group_id", attrGroupId);
                List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.list(attrgroupRelationEntityQueryWrapper);
                if (attrAttrgroupRelationEntities != null && attrAttrgroupRelationEntities.size() > 0) {
                    ArrayList<AttrEntity> attrEntities = new ArrayList<>();
                    for (AttrAttrgroupRelationEntity attrAttrgroupRelationEntity : attrAttrgroupRelationEntities) {
                        Long attrId = attrAttrgroupRelationEntity.getAttrId();
                        //通过attr_id查询pms_attr
                        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
                        attrEntityQueryWrapper.eq("attr_id", attrId);
                        AttrEntity attrEntity = attrService.getById(attrId);
                        attrEntities.add(attrEntity);
                    }
                    if(attrEntities!=null &&attrEntities.size()>0) {
                        attrGroupWithAttrsOutVo.setAttrs(attrEntities);
                    }
                }
                attrGroupWithAttrsOutVos.add(attrGroupWithAttrsOutVo);
            }
        }
        return attrGroupWithAttrsOutVos;
    }
}